<template>
  <Dialog
    content-class="upload-dialog"
    v-model="syncedShow"
    :title="dialogTitle"
    width="904"
  >
    <template #headerAppend>
      <v-icon @click="downloadFile" class="icon pointer" color="#fff">
        mdi-file-download
      </v-icon>
      <v-icon @click="deleteFile" class="icon pointer" color="#fff">
        mdi-delete
      </v-icon>
      <v-icon @click="close" class="icon pointer" color="#fff">
        mdi-close
      </v-icon>
    </template>
    <v-spacer class="upload-content-wrap pa-2">
      <v-col class="header pa-0">
        <v-row v-if="step === 1" no-gutters class="space-end">
          <v-col>
            <v-radio-group
              v-model="selectedFileType"
              hide-details
              class="ma-0 pa-0"
              row
            >
              <v-radio
                color="#3B4765"
                class="file-type-radio"
                :class="selectedFileType === radio.value ? 'active' : ''"
                v-for="radio in fileTypeRadio"
                :key="radio.value"
                :value="radio.value"
                :label="radio.label"
                on-icon="mdi-check-circle"
              ></v-radio>
            </v-radio-group>
          </v-col>
        </v-row>
        <div v-else-if="step === 2 && currentAttachment" class="text-left ml-3">
          {{ currentAttachment.number }}
        </div>
      </v-col>
      <v-col class="pa-0 pt-2">
        <v-card class="images-wrap" height="660" flat no-gutters>
          <v-col
            v-if="step === 2 && currentAttachment"
            class="text-left px-0 py-1"
          >
            {{ currentAttachment.date }}
          </v-col>
          <div v-if="step === 1">
            <v-spacer
              v-for="attachment in syncedAttachmentList"
              :key="attachment.date"
              class="mb-4"
            >
              <v-col class="text-left pa-0">
                <h6>
                  {{ attachment.number }}
                </h6>
              </v-col>
              <v-col class="text-left px-0 py-1">
                {{ attachment.date }}
              </v-col>
              <v-col class="pa-0">
                <div class="images clearfix">
                  <v-row no-gutters>
                    <v-col
                      class="image-wrap flex-grow-0"
                      v-for="file in attachment.fileList"
                      :key="file.id"
                    >
                      <v-checkbox
                        v-model="selectedFiles"
                        :value="file"
                        class="checkbox"
                        color="#556282"
                        hide-details
                        off-icon="mdi-checkbox-blank"
                      ></v-checkbox>
                      <i class="ornamental"></i>
                      <img
                        @click="showViewAttachment(attachment, file)"
                        v-if="file.ext === 'jpg' || file.ext === 'png'"
                        :alt="file.title"
                        :src="file.src"
                        class="image"
                      />
                      <span v-else>
                        {{ file.title }}
                      </span>
                    </v-col>
                  </v-row>
                </div>
              </v-col>
            </v-spacer>
          </div>
          <ViewAttachment
            v-else-if="step === 2"
            :attachment="viewFile"
          ></ViewAttachment>
        </v-card>
      </v-col>
      <v-col class="upload-wrap px-0 pt-4 pb-2">
        <v-file-input
          v-if="step === 1"
          accept="image/*"
          class="upload-btn"
          hide-input
          multiple
          prepend-icon="mdi-upload"
          truncate-length="15"
          @change="uploadFile"
        >
        </v-file-input>
        <v-btn
          v-else-if="step === 2"
          @click="step = 1"
          color="#EB9B31"
          width="40"
          height="40"
          elevation="0"
          fab
        >
          <v-icon color="#fff"> mdi-arrow-left </v-icon>
        </v-btn>
      </v-col>
    </v-spacer>
  </Dialog>
</template>

<script lang="ts">
import { Vue, Component, PropSync } from "vue-property-decorator";
import { getDate } from "@/common/constants/Utils";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import ViewAttachment from "@/components/Project/Upload/ViewAttachment.vue";
import { IAttachment, IFile } from "@/components/Project/index";
import { readerFile } from "@/common/constants/Utils";
import VFileInput from "vuetify/src/components/VFileInput";
type VFileInputInstance = InstanceType<typeof VFileInput>;

@Component({
  components: {
    Dialog,
    ViewAttachment,
  },
})
export default class Upload extends Vue {
  @PropSync("show", {
    type: Boolean,
    default: false,
  })
  syncedShow!: boolean;

  @PropSync("attachmentList", {
    type: Array,
    default: () => [],
  })
  syncedAttachmentList!: Array<IAttachment>;

  get dialogTitle() {
    return this.step === 1 ? "Upload Attachment" : "View Attachment";
  }

  viewFile: IFile | null = null;
  currentAttachment: IAttachment | null = null;

  showViewAttachment(attachment: IAttachment, file: IFile) {
    this.viewFile = file;
    this.currentAttachment = attachment;
    this.step = 2;
  }

  step = 1;

  selectedFileType = "";

  fileTypeRadio = [
    {
      label: "PDF",
      value: "PDF",
    },
    {
      label: "jpg",
      value: "jpg",
    },
    {
      label: "Excel",
      value: "Excel",
    },
    {
      label: "Select all",
      value: "",
    },
  ];

  clickFileInput() {
    (this.$refs.fileInput as VFileInputInstance).$refs.input.click();
  }

  async uploadFile(files: HTMLInputElement["files"]) {
    if (!files || files.length <= 0) return;
    for (let i = 0; i < files.length; i++) {
      const currentAttachment = this.syncedAttachmentList.find((item) => {
        return item.date === getDate("-");
      });
      const file = files[i];
      const reader: FileReader = await readerFile(file);
      if (!reader.error) {
        // 文件转base64成功
        const fileName = file.name;
        const lastIndex = fileName.lastIndexOf(".");
        const ext = fileName.substring(lastIndex + 1).toLowerCase();
        console.log(reader.result);
        const fileObj = {
          id: `${new Date().getTime()}${file.name}`,
          ext: ext,
          src: reader.result as string,
          title: file.name,
        };
        if (currentAttachment) {
          currentAttachment.fileList.push(fileObj);
        } else {
          const attachment = {
            id: String(new Date().getTime()),
            number: "DL-20211209001",
            date: getDate("-"),
            fileList: [fileObj],
          };
          this.syncedAttachmentList.push(attachment);
        }
      } else {
        // 文件转base64失败
        this.SweetAlertService.error("Upload Error");
      }
    }
  }

  selectedFiles: IFile[] = [];

  deleteFile() {
    const viewFile = this.viewFile;
    if (this.step === 2 && viewFile && this.currentAttachment) {
      const viewFileIndex = this.currentAttachment.fileList.indexOf(viewFile);
      this.currentAttachment.fileList.splice(viewFileIndex, 1);
      this.viewFile = null;
      this.currentAttachment = null;
      this.step = 1;
    } else if (this.step === 1) {
      // this.selectedFiles.forEach((file) => {
      //   this.syncedItem.attachment.attachmentList.forEach((attachment) => {
      //     const fileIndex = attachment.fileList.indexOf(file);
      //     attachment.fileList.splice(fileIndex, 1);
      //   });
      // });
      this.selectedFiles = [];
    }
  }

  downloadFile() {
    if (this.step === 1) {
      this.selectedFiles.forEach((file) => {
        this.download(file.src, file.title, file.ext);
      });
    } else if (this.step === 2) {
      if (this.viewFile) {
        this.download(
          this.viewFile.src,
          this.viewFile.title,
          this.viewFile.ext
        );
      }
    }
  }

  download(url: string, fileName: string, ext: string) {
    fetch(url).then((res) => {
      res.blob().then((blob) => {
        const aTag = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        aTag.href = href;
        aTag.download = `${fileName}.${ext}`;
        aTag.click();
      });
    });
  }

  close() {
    this.syncedShow = false;
  }
}
</script>

<style lang="scss" scoped>
@import "@/components/Project/Upload/Upload.scss";
</style>
